<template>
  <div class="content">
    <div id="div1"></div>
  </div>
</template>
<script>
import E from 'wangeditor';
import SparkMD5 from 'spark-md5';
import insertImage from './select';
export default {
  data() {
    return {
      editor: null,
      currentRange: '',
      _parentElem: '',
      doc: null,
      supportRange: typeof document.createRange === 'function',
      params: {
        html:
          '<p><br></p><p><img title="e34dd5a8ce4b22ccfb9436236f60ecef" >范德萨发生的</p><p>范德萨范德萨</p><p>范德萨范德萨发都是发送到发送到发送到</p><p><img title="b0c053c3f4d2c56dcadf1982af4dc2e4" >是的撒</p><p><b>大师法无法玩法为沙发</b></p><p><i><b>大萨达撒</b>dsa</i></p><p><i><br></i></p><p><img title="f970c9054989bdf58977a3b8afc491d0" ></p>',
        list: [
          {
            b0c053c3f4d2c56dcadf1982af4dc2e4: require('../assets/images/222.jpg')
          },
          {
            f970c9054989bdf58977a3b8afc491d0: require('../assets/images/333.jpg')
          },
          {
            e34dd5a8ce4b22ccfb9436236f60ecef: require('../assets/images/111.jpg')
          }
        ]
      }
    };
  },

  mounted() {
    this.editor = new E('#div1');

    let vm = this;
    console.log(vm.uploadImg);
    this.editor.config.showLinkImg = false;
    this.editor.config.customUploadImg = this.uploadImg;
    this.editor.config.uploadImgMaxSize = 2 * 1024 * 1024;
    this.editor.config.onchange = function(newHtml) {
      let arr = [];
      console.log(newHtml.replace(/src=(?:"\s*([^"]*)\s*"|'\s*([^']*)\s*'|(\S+))/g, ''));
      vm.getCursortPosition(document.querySelector('.w-e-text')).insertNode;
    };
    this.editor.create();
    this.doc = document.getElementById('div1').querySelector('.w-e-text');
    this.doc.onmouseup = function() {
      vm.saveSelection();
    };
    this.doc.onkeyup = function() {
      vm.saveSelection();
    };
  },
  methods: {
    formate(item) {
      let str = '';
      console.log(item);
      if (!item.children || item.children.length === 0) {
        str = item;
        return str;
      } else {
        return this.formate(item.children[0]);
      }
    },
    // 上传图片
    uploadImg(resultFiles, insertImgFn) {
      console.log(resultFiles);
      let vm = this;

      resultFiles.forEach(async val => {
        let uuid = await this.uuid(val);
        console.log(this.uuid(val));
        console.log(uuid);
        // 将图片转化为base64本地预览
        var reader = new FileReader();
        reader.onloadend = function() {
          vm.insertImage(
            `<img width='200' height='100' controls="controls" &title=${uuid} src='${this.result}'>`
          );
        };
        if (val) {
          reader.readAsDataURL(val);
        }
      });
    },
    getCursortPosition(element) {
      var doc = element.ownerDocument || element.document;
      var win = doc.defaultView || doc.parentWindow;
      var sel;
      if (typeof win.getSelection != 'undefined') {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
          var range = win.getSelection().getRangeAt(0);
          console.log(range);
        }
      }
      return range;
    },
    // 生成uuid
    uuid(file) {
      return new Promise((resolve, reject) => {
        var fileReader = new FileReader();
        var blobSlice =
          File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
        var chunkSize = 2097152;
        // read in chunks of 2MB
        var chunks = Math.ceil(file.size / chunkSize);
        var currentChunk = 0;
        var spark = new SparkMD5();
        fileReader.onload = function(e) {
          console.log('read chunk nr', currentChunk + 1, 'of', chunks);
          spark.appendBinary(e.target.result); // append binary string
          currentChunk++;

          if (currentChunk < chunks) {
            loadNext();
          } else {
            resolve(spark.end());
          }
        };

        function loadNext() {
          var start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;
          fileReader.readAsBinaryString(blobSlice.call(file, start, end));
        }

        loadNext();
      });
    },
    $(a) {
      return document.getElementById(a);
    },
    getCurrentRange() {
      var selection, range;
      if (this.supportRange) {
        selection = document.getSelection();
        if (selection.getRangeAt && selection.rangeCount) {
          range = document.getSelection().getRangeAt(0);
          this._parentElem = range.commonAncestorContainer;
        }
      } else {
        range = document.selection.createRange();
        this._parentElem = range.parentElement();
      }
      return range;
    },
    saveSelection() {
      this.currentRange = this.getCurrentRange();
    },
    restoreSelection() {
      if (!this.currentRange) {
        return;
      }
      var selection, range;
      if (this.supportRange) {
        selection = document.getSelection();
        selection.removeAllRanges();
        selection.addRange(this.currentRange);
      } else {
        range = document.selection.createRange();
        range.setEndPoint('EndToEnd', this.currentRange);
        if (this.currentRange.text.length === 0) {
          range.collapse(false);
        } else {
          range.setEndPoint('StartToStart', this.currentRange);
        }
        range.select();
      }
    },
    insertImage(html) {
      this.restoreSelection();
      if (document.selection) {
        this.currentRange.pasteHTML(html);
      } else {
        document.execCommand('insertHTML', false, html);
      }
      this.saveSelection();
    }
  }
};
</script>
